<template>
	<view>
		<!-- :style="{'grid-template-rows':gridTempalteRows}" -->
		<view class="container" @tap="togglePicker(0)">

			<view class="history-tips" v-if="isShowHistoryMsgTips">加载历史消息。。。</view>
			<!-- 1，消息主要内容 -->
			<!-- 
				下拉刷新参数
				@refresherpulling="onPulling" 
				@refresherrefresh="onRefresh"
				@refresherrestore="onRestore" 
				@refresherabort="onAbort" 
				refresher-default-style="white"
				:refresher-threshold="refresherThreshold" 
				refresher-background="#F3F3F3"
				refresher-enabled="true" 
				:refresher-triggered="triggered"
			 -->
			<view class="message" :style="{'height':scrollHeight}">
				<view style="height: 10px;"></view>
				<scroll-view ref="scrollViewRef" :upper-threshold="50" :scroll-top="scrollTop"
					:scroll-into-view="scrollViewId" scroll-y style="height: calc(100% - 20px);" show-scrollbar="true"
					:scroll-with-animation="scrollWithAnimation" @scroll="onScroll" @scrolltolower="onScrolltolower">

					<view v-for="(item,index) in chatList" :key="index" :id="'msg' + item.msgId">
						<view>{{'msg' + item.msgId}}</view>
						<chat-msg-item @imgLoad="imgLoad" :chatItem="item" :chatItemIndex="index" @showImg="showImg"
							@showRedPkg="showRedPkg" @gotoUserSet="gotoUserSet" @handleAudio="handleAudio"
							@longpressItem="longpressItem">

							<!-- 时间处理器 -->
							<template v-slot:chatTime>
								<view>{{computeDate(item.time , index)}}</view>
							</template>

						</chat-msg-item>
					</view>
					<view id="bottom-anchor"></view>
				</scroll-view>
				<view style="height: 10px;"></view>
			</view>

			<!-- 2，输入框框主要内容 -->
			<view class="send" @tap.prevent.stop="" v-if="!isSendMsg">
				<view class="send-row">
					<!--语音切换-->
					<image v-if="isEdit" @tap="toggleEdit(false)" src="./static/img/send/voice.svg" class="icon">
					</image>
					<image v-else @tap="toggleEdit(true)" src="./static/img/send/keyboard.svg" class="icon"></image>
					<!--语音切换-->
					<!-- <form @submit="submitInput">
				</form> -->
					<input v-if="isEdit" @focus="inputFocus" :focus="isFocus" :cursor-spacing="40"
						:adjust-position="isAdjustPosition" confirm-type="send" cursor-spacing="40"
						@confirm="sendMessage" @input="textareaBInput" v-model="content" class="input"
						placeholder="请文明发言..." />

					<view v-else @touchstart="micTouchStart" @touchmove="micTouchMove" @touchcancel="micTouchCancel"
						@touchend="micTouchEnd" class="input" style="text-align: center;">
						按住开吼
					</view>

					<!--表情-->
					<image @tap="togglePicker(200, 'emoji')" src="./static/img/send/emoji.svg" class="icon"></image>
					<!--发送-->
					<view @touchend.prevent="sendMessageByBtn" v-if="isShowSendBtn" class="btn">发送</view>
					<!--附件-->
					<image @tap="togglePicker(150, 'file')" v-else src="./static/img/send/add.svg" class="icon">
					</image>
				</view>

				<view class="send-new-msg" @click="gotoBottomByTips"
					:style="{'visibility':newMsgVisibility,'opacity':newMsgOpacity}">
					<text>有新消息</text>
				</view>

				<transition name="fade">
					<!-- 3，工具栏框 -->
					<view v-if="showFile" class="send-file" @tap.prevent.stop="">
						<view class="send-file-list">
							<view class="file-box">
								<view class="file-box-item" @tap="chooseIamgeFromAlbum(['album'])">
									<image src="./static/img/file/02.svg" class="icon"></image>
									<view class="text">相册</view>
								</view>
							</view>
							<view class="file-box">
								<view class="file-box-item" @tap="chooseIamgeFromCamera(['camera'])">
									<image src="./static/img/file/03.svg" mode="widthFix" class="icon"></image>
									<view class="text">拍摄</view>
								</view>
							</view>
							<view class="file-box">
								<view class="file-box-item" @tap="sendRedPkg">
									<image src="./static/img/file/04.svg" mode="widthFix" class="icon"></image>
									<view class="text">红包</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 4，表情库 -->
					<view v-if="showEmoji" class="emoji" @tap.prevent.stop="">
						<chat-send-emoji @clickEmoji="clickEmoji" :height="emojiHight"></chat-send-emoji>
					</view>
				</transition>
			</view>
			<view class="send" @tap.prevent.stop="" v-else>
				<view class="send-row">
					<image src="./static/img/send/voice.svg" class="icon"></image>
					<view class="input" style="text-align: center;">
						{{sendTitle}}
					</view>
					<!--表情-->
					<image src="./static/img/send/emoji.svg" class="icon"></image>
					<!--附件-->
					<image src="./static/img/send/add.svg" class="icon">
					</image>
				</view>
			</view>

			<!-- 5，长按弹框 -->
			<chat-con-tool :popButton="popButton" :showShade="showShade" :showPop="showPop" :popStyle="showHeightStyle"
				@pickerMenu="pickerMenu" @hidePop="closeShowTool"></chat-con-tool>

			<!-- 6，好友添加框 -->
			<chat-add v-if="!isGx" @sendAddUser="sendAddUser"></chat-add>

			<!-- 7，发送语音动画 -->
			<chat-voice-icon :isShow="isShowVoiceIcon" :titleText="voiceIconTitle"
				:voiceBgColor="voiceBgColor"></chat-voice-icon>

			<!-- 8，@框 -->
			<chat-at-animation @selectUser="selectUser" :share="isShowAtGroup" :groupUsers="groupUsers"
				@display="closeAtGroup"></chat-at-animation>
		</view>
	</view>
</template>

<script>
	//1，引入子组件
	import chatSendEmoji from './child/chat-send-emoji.vue'
	import chatMsgItem from './child/chat-msg-item.vue'
	import chatConTool from './child/chat-con-tool.vue'
	import chatAdd from './child/chat-add.vue'
	import chatVoiceIcon from './child/chat-voice-icon/index.vue'
	import chatAtAnimation from './child/chat-at-animation.vue'

	//2，时间工具处理
	import {
		handleTime,
		timeago
	} from './utils/time.js'

	//3，引入uniapp工具
	import {
		chooseIamge,
		chooseImageFromCamera
	} from '@/api/uniapp/uni.js'

	//4，引入文件网络请求
	import {
		uploadFile
	} from '@/api/http/common.js'
	import {
		queryGroupUsers
	} from '@/api/http/msg/group.js'

	//5，语音发送参数
	var recordManager = null;
	var recordTimeInterval = null;

	export default {
		props: {
			//1，聊天信息
			chatList: {
				type: Array,
				default: () => []
			},
			//2，图片信息
			imgList: {
				type: Array,
				default: () => []
			},
			//3，聊天对象信息
			msgObjectData: {
				type: Object,
				default: () => {}
			},
			//4，添加好友框
			isGx: {
				type: Boolean,
				default: true
			},
			//5，是否能够发送消息
			isSendMsg: {
				type: Boolean,
				default: false
			},
			//6，展示框内容
			sendTitle: {
				type: String,
				default: '群聊禁言'
			},
			//7，是否展示历史消息
			isShowHistoryMsgTips: {
				type: Boolean,
				default: false
			}
		},

		components: {
			chatSendEmoji,
			chatMsgItem,
			chatConTool,
			chatAdd,
			chatVoiceIcon,
			chatAtAnimation
		},
		data() {
			return {
				gridTempalteRows: '',
				bottomHeight: 110, //底部输入框初始高度

				scrollHeight: 'auto', //消息主要内容高度
				scrollViewId: '', //页面滑动到的高度
				statusBarHeight: 0, // 状态栏高度
				changeTranslateY: 0, //切换高度

				isEdit: true, //展示输入框
				isFocus: false, //输入框获取焦点
				content: '', //输入框内容

				showEmoji: false, //是否展示表情框
				showFile: false, //是否展示工具框
				showVoice: false, //是否展示语音动画

				userId: uni.getStorageSync('userId'),

				showPopChatItem: {}, //长按操作的对象
				//长按弹出
				showShade: false,
				showPop: false,
				showHeightStyle: '',
				popButton: [{
					id: 1,
					text: '撤回',
					img: require('@/static/img/msg/tool/01.svg')
				}, {
					id: 2,
					text: '删除',
					img: require('@/static/img/msg/tool/02.svg')
				}],

				//页面宽高信息
				screenHeight: 0,
				windowWidth: 0,
				windowHeight: 0,
				//底部输入框高度
				sendHeight: 50,

				//下拉刷新参数
				/* triggered: '',
				_freshing: '',
				refresherThreshold: 45, */

				//发送语音参数

				voiceIconTitle: '正在录音...', //语音动画下的文字
				voiceBgColor: '#05C160', //录音动画背景颜色
				voiceTime: 0, //语音计时
				voiceInterval: '', //语音定时器
				recorderManager: uni.getRecorderManager(), //录音参数

				recordTime: 0, //语音时间
				isRecording: false, //开启语音发送
				isShowVoiceIcon: false, //是否按住语音说话按钮

				emojiHight: '200', //表情框可滑动高度
				moreToolHeight: 0, //工具栏高度，

				//at展示框
				isShowAtGroup: false,
				//艾特信息
				atItem: '',
				//群聊成员
				groupUsers: [],

				inputIsEject: false, //弹出框是否弹出

				oldChatListLength: 0, //之前位置
				scrollWithAnimation: false, //是否开启滑动动画
				scrollTop: 0, //滚动条位置

				isShowSendBtn: false,
				isAdjustPosition: false, //页面网上顶

				newMsgVisibility: 'hidden',
				newMsgOpacity: 0,
				// distanceBottom: 0, //距离底部的高度
				// bottomScrollTop: 0, // 距离顶部的高度
				nowScrollTop: 0, //当前距离顶部高度
				messageHeight: 0, //消息列表高度
				nowScrollHeight: 0, //当前可滑动高度
			}
		},
		watch: {
			content() {
				this.isShowSendBtn = this.content.length > 0
				//console.log(123)
			}
		},

		methods: {
			//0，获取页面高度
			getPageInfo() {
				uni.getSystemInfo({
					success: (res) => {
						this.$nextTick(() => {
							this.screenHeight = res.windowHeight
							this.windowWidth = res.windowWidth
							this.windowHeight = res.windowHeight

							this.setScrollHeight()
						})
					}
				})
			},

			//1，设置scroll的高度
			setScrollHeight(chaneBottomHeight = 0, isgotoBottom = false, timegotoBottom = 50, isShowJp = false) {

				// #ifdef MP-WEIXIN
				this.scrollHeight = `calc(100vh - 110rpx - ${chaneBottomHeight}px)`
				// #endif
				// #ifdef APP-PLUS
				let systemInfo = uni.getSystemInfoSync();
				if (systemInfo.platform == 'ios') {
					this.isAdjustPosition = true

					if (isShowJp) {
						this.scrollHeight = `calc(100vh - 110upx)`
					} else {
						this.scrollHeight = `calc(100vh - 110upx - ${chaneBottomHeight}px)`
					}
				} else {
					this.scrollHeight = `calc(100vh - 110upx - ${chaneBottomHeight}px)`
				}

				// #endif
				// #ifdef H5
				this.scrollHeight = `calc(100vh - 110upx - 44px - ${chaneBottomHeight}px)`
				// #endif

				if (isgotoBottom) {
					this.initScrollBar(timegotoBottom)
				}
			},
			onScroll(event) {
				var that = this
				that.nowScrollTop = event.detail.scrollTop
				if (event.detail.scrollTop < 10) {
					//上拉加载更多消息
					console.log('上拉加载更多消息')
					setTimeout(() => {
						that.$emit('getHistoryMsg')
					}, 30)

					return
				}
				that.nowScrollHeight = event.detail.scrollHeight
				if (event.detail.scrollHeight - event.detail.scrollTop - that.messageHeight < 260) {
					//滚动到低于，150像素，则关闭新消息提示
					setTimeout(() => {
						this.closeNewTips()
					}, 30)
				}

			},

			onScrolltolower(e) {
				//console.log('滚动到底部了')
				//滚动到底部的时候，设置距离顶部的高度
				// var that = this
				// setTimeout(() => {
				// 	that.bottomScrollTop = e.scrollTop
				// }, 100)
				//this.closeNewTips()
				//到底部，则改变总长度
				this.$emit('changeMsgListLeng', true)
			},

			//2，滚动到最底部
			initScrollBar(time = 30, isSendMsg = true) {
				if (!isSendMsg) {
					var that = this
					// 获取 消息列表高度
					uni.createSelectorQuery().select('.message').boundingClientRect((res) => {
						that.messageHeight = res.height
						if (that.nowScrollHeight - that.nowScrollTop - res.height > 260) {
							//距离底部超过300 px不用滚动到底部
							console.log('距离底部超过260 px不用滚动到底部')
							that.showNewTips()

							//到底部，则改变总长度
							that.$emit('changeMsgListLeng', false)
							return
						} else {
							//到底部，则改变总长度
							that.$emit('changeMsgListLeng', true)
							that.gotoBottomFunction(time)
						}
					}).exec()
				} else {
					this.gotoBottomFunction(time)
				}



				/* this.$nextTick(() => {
					setTimeout(() => {
						this.scrollViewId = 'msg' + (this.chatList.length - 1)
						setTimeout(() => {
							this.scrollViewId = ''
						}, 30)
					}, time)
				}) */
				/* setTimeout(() => {
					this.scrollViewId = ''
					setTimeout(() => {
						this.scrollViewId = 'bottom'
						setTimeout(() => {
							this.scrollViewId = ''
						}, time)
					}, time)
				}, 50) */
			},
			gotoBottomFunction(time = 50, scrollViewId = 'bottom-anchor') {
				var that = this
				setTimeout(() => {
					if (that.chatList.length == 0) {
						return
					}
					//console.log('滚动到最底部')
					that.scrollViewId = '';
					that.$nextTick(function() {
						let len = that.chatList.length - 1
						that.scrollViewId = scrollViewId
					})
				}, time)
			},
			gotoMsgView(selector) {
				//console.log(selector)
				uni.createSelectorQuery().select(selector).boundingClientRect(data => {
					console.log(data)
					const targetTop = data.top; // 获取距离顶部的距离
					const scrollDistance = targetTop + 300; // 距离减去30px后的位置
					this.scrollViewToId(scrollDistance); // 调用滚动方法
				}).exec();
			},
			scrollViewToId(distance) {
				console.log(distance)
				this.scrollTop = distance
				this.$refs.scrollViewRef.scrollTo({
					scrollTop: distance,
					duration: 50, // 滚动动画时长
					easingFunc: "easeIn" // 滚动动画缓动函数
				});
			},

			//3，语音输入框切换
			toggleEdit(bool) {
				this.isEdit = bool
				this.isFocus = bool
				this.setScrollHeight(0, true, 20)
			},
			//4，表情库和工具框展示
			togglePicker(height = 0, type = '') {
				//this.initScrollBar(10)
				this.showEmoji = false
				this.showFile = false
				let status = height > 0 ? true : false
				var that = this

				uni.onKeyboardHeightChange(res => {
					if (res.height > 0) {
						return
					} else {
						switch (type) {
							case 'emoji':
								that.isEdit = true
								//this.isFocus = true
								that.showEmoji = status;
								break
							case 'file':
								that.showFile = status;
								break
						}
						if (that.moreToolHeight > 0 && height > 0) {
							height = that.moreToolHeight
						}
						if (status) {
							that.setScrollHeight(height, true, 150)
						} else {
							that.setScrollHeight(height, false, 150)
						}
						return
					}
				})

				switch (type) {
					case 'emoji':
						that.isEdit = true
						//this.isFocus = true
						that.showEmoji = status;
						break
					case 'file':
						that.showFile = status;
						break
				}
				if (that.moreToolHeight > 0 && height > 0) {
					height = that.moreToolHeight
				}
				if (status) {
					that.setScrollHeight(height, true, 150)
				} else {
					that.setScrollHeight(height, false, 150)
				}

			},

			//5，输入框监听
			inputFocus(e) {
				var iosHeight = uni.getSystemInfoSync().safeAreaInsets
				//console.log(iosHeight)
				if (e.detail.height > 0) {
					this.inputIsEject = true
					this.showEmoji = false;
					this.showFile = false;
					// if (this.moreToolHeight == 0) {
					// 	this.moreToolHeight = e.detail.height
					// 	this.emojiHight = parseFloat(e.detail.height) + 20 + ''
					// }
					this.setScrollHeight(e.detail.height, false, 50, true)
				} else {
					this.inputIsEject = false
					this.setScrollHeight(e.detail.height, false, 50)
				}
				//console.log(e.detail.height)
				//this.setScrollHeight(e.detail.height, false, 50)

				uni.onKeyboardHeightChange(res => {
					this.inputIsEject = true
					if (res.height > 0) {
						// if (this.moreToolHeight == 0) {
						// 	this.moreToolHeight = e.detail.height
						// 	this.emojiHight = parseFloat(e.detail.height) + 20 + ''
						// }

						this.showEmoji = false;
						this.showFile = false;
						this.setScrollHeight(e.detail.height, false, 50, true)
					} else {
						this.inputIsEject = false
						this.setScrollHeight(res.height, false, 50)
					}
					//console.log(res.height)
					//this.setScrollHeight(res.height, false, 50)
				})
			},

			submitInput(e) {
				console.log(123123)
				console.log(e)
			},

			//6，点击表情，在输入框中显示
			clickEmoji(e) {
				this.content += e
			},

			//7，时间显示工具
			computeDate(createTime, index) {
				if (createTime) {
					if (uni.getSystemInfoSync().platform === 'android') {
						//console.log('运行Android上')
						var datetime = new Date(createTime)
						let date = new Date()

						if (index > 0) {
							//获取上一个
							let beforetime = this.chatList[index - 1].time
							let beforetimestrap = new Date(beforetime)
							if ((datetime - beforetimestrap) > 180000) {
								return this.getTime(createTime)
							} else {
								return ''
							}
						} else {
							return this.getTime(createTime)
						}

					} else {
						//console.log('运行iOS上')
						var datetime = new Date(createTime.replace(/-/g, '/'))
						let date = new Date()

						if (index > 0) {
							//获取上一个
							let beforetime = this.chatList[index - 1].time
							let beforetimestrap = new Date(beforetime.replace(/-/g, '/'))
							if ((datetime - beforetimestrap) > 180000) {
								return this.getTime(createTime.replace(/-/g, '/'))
							} else {
								return ''
							}
						} else {
							return this.getTime(createTime.replace(/-/g, '/'))
						}
					}
				} else {
					return ''
				}
			},
			//7.1，获取时间
			getTime(time) {
				if (uni.getSystemInfoSync().platform === 'android') {
					//console.log('运行Android上')
					return handleTime(time)
				} else {
					//console.log('运行iOS上')
					return handleTime(time.replace(/-/g, '/'))
				}
			},

			//8，文本消息发送
			sendMessage(e) {
				if (e.detail.value == '' || e.detail.value == null) {
					return
				}

				if (this.atItem == '') {
					this.sendMsgByUser(e.detail.value, 1)
					//console.log(e)
				} else {

					if (e.detail.value.indexOf('@' + JSON.parse(this.atItem).nickname) !== -1) {
						var atMsg = JSON.parse(this.atItem)
						atMsg.atMsgNew = e.detail.value.substring(JSON.parse(this.atItem).nickname.length + 1, e.detail
							.value.length)
						//console.log(atMsg)
						this.sendMsgByUser(JSON.stringify(atMsg), 31)
						this.atItem = ''
					} else {
						this.atItem = ''
						this.sendMsgByUser(e.detail.value, 1)
					}

				}
				setTimeout(() => {
					//清空聊天框
					this.content = ''
				}, 10)




				/* if (e.detail.value == '' || e.detail.value == null) {
					return
				}
				this.sendMsgByUser(e.detail.value, 1)
				//清空聊天框
				this.content = '' */
				//console.log(e)
				/* setTimeout(() => {
					//清空聊天框
					this.content = ''
				}, 10) */
			},
			//8.1，按钮
			sendMessageByBtn() {
				if (this.content == '' || this.content == null) {
					return
				}
				this.sendMsgByUser(this.content, 1)
				//清空聊天框
				this.content = ''
				//console.log(e)
				/* setTimeout(() => {
					//清空聊天框
					this.content = ''
				}, 10) */
			},
			//8.2，关闭@弹框
			closeAtGroup() {
				this.isShowAtGroup = false
			},
			//8.3，点击@成员
			selectUser(e) {
				//console.log(e)
				this.atItem = JSON.stringify(e)
				//console.log(atItem)
				this.isShowAtGroup = false
				this.content = this.content.substring(0, this.content.length - 1)
				//console.log(this.content)
				this.content += '@' + e.nickname
			},
			//9，文本输入监听
			textareaBInput(e) {
				if (this.msgObjectData.type == 2) {
					return
				}
				var inputText = e.detail.value
				//console.log(inputText)
				if (inputText == '@') {
					//console.log('添加@成员')
					queryGroupUsers(this.msgObjectData.id, '', '', '1').then(res => {
						if (res.data.pubInfo.code !== 0) {
							return uni.$showMsg(res.data.pubInfo.message);
						}
						this.groupUsers = res.data.busInfo

						//隐藏键盘
						uni.hideKeyboard()
						this.isShowAtGroup = true
					})

				}
			},

			//9.1，发送图片
			chooseIamgeFromAlbum() {
				var that = this
				chooseIamge('album').then(res => {
					const filePaths = res.tempFilePaths
					for (let i = 0; i < filePaths.length; i++) {
						//图片上传
						uploadFile(filePaths[i]).then(result => {
							if (result.data.pubInfo.code !== 0) {
								return uni.$showMsg(result.data.pubInfo.message);
							}
							//var  = result.data.busInfo
							that.sendMsgByUser(result.data.busInfo, 2)
						})

						//this.send(filePaths[i], 1)
					}
				})
			},
			//9.2，照相发送
			chooseIamgeFromCamera() {
				var that = this
				chooseImageFromCamera().then(res => {
					uploadFile(res).then(result => {
						if (result.data.pubInfo.code !== 0) {
							return uni.$showMsg(result.data.pubInfo.message);
						}
						//var  = result.data.busInfo
						that.sendMsgByUser(result.data.busInfo, 2)
					})
				})
			},
			//9.3，图片加载成功
			imgLoad() {},
			//9.4，查看图片
			showImg(e) {
				var that = this
				uni.previewImage({
					current: e.news,
					urls: this.imgList,
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');

							uni.downloadFile({
								url: that.imgList[data.index],
								success: (res) => {
									if (res.statusCode === 200) {
										uni.saveImageToPhotosAlbum({
											filePath: res.tempFilePath,
											success: function() {
												//uniapp提供的消息提示框。
												uni.showToast({
													title: "保存成功",
													icon: "success"
												});
											},
											fail: function() {
												uni.showToast({
													title: "保存失败，请稍后重试",
													icon: "none"
												});
											}
										});
									}
								}
							})

						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				})
			},

			//10，点击好友头像设置
			gotoUserSet(item) {
				this.$emit("gotoUserSet", item)
			},

			//11，发送红包
			sendRedPkg() {
				if (!uni.getStorageSync('identifyCheck')) {
					return uni.$showMsg('请先进行实名认证！')
				}

				uni.navigateTo({
					url: '/subpkg/msg/red-pkg/red-pkg-send/red-pkg-send?msgObject=' + JSON.stringify(this
						.msgObjectData)
				})
			},
			//11.1，打开红包
			showRedPkg(item) {
				this.$emit("showRedPkg", item)
			},

			//12，长按弹框
			longpressItem(item, chatItem) {
				//console.log(chatItem)
				if (chatItem.isWithdraw && chatItem.sendId == this.userId) {
					//可以撤回
					this.popButton = [{
						id: 1,
						text: '撤回',
						img: require('@/static/img/msg/tool/01.svg')
					}, {
						id: 2,
						text: '删除',
						img: require('@/static/img/msg/tool/02.svg')
					}]
				} else {
					//无法撤回
					this.popButton = [{
						id: 2,
						text: '删除',
						img: require('@/static/img/msg/tool/02.svg')
					}]
				}


				this.showPopChatItem = chatItem
				//计算光标高度（距离顶部导航栏的距离）
				var height = parseInt(item.pageY)
				var width = parseInt(item.pageX)
				var bottomHeight = (this.windowHeight - this.sendHeight - 50)
				var leftWidth = this.windowWidth * 0.7
				var rightWidth = this.windowWidth * 0.22
				//this.windowWidth - width

				if (height < 45) {
					//1，如果小于弹框高度则固定位置
					if (width > leftWidth) {
						this.showHeightStyle = `top:60px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `top:60px;left:${width}px;`
					}
				} else if (bottomHeight < height) {
					//2，如果，在底部的话则固定在上面
					if (width > leftWidth) {
						this.showHeightStyle = `bottom:${this.sendHeight + 30}px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `bottom:${this.sendHeight + 30}px;left:${width}px;`
					}
				} else {
					if (width > leftWidth) {
						this.showHeightStyle = `top:${height}px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `top:${height}px;left:${width}px;`
					}
				}

				this.showShade = true;
				this.$nextTick(() => {
					setTimeout(() => {
						this.showPop = true;
					}, 10);
				});
			},
			//12.1，关闭弹框
			closeShowTool() {
				this.showPop = false;
				//this.pickerUserIndex = -1;
				setTimeout(() => {
					this.showShade = false;
				}, 10);
			},
			//12.2选择其中的一个
			pickerMenu(item) {
				//console.log(this.showPopChatItem)
				if (item.id == 2) {
					this.$emit('closeUserMsg', this.showPopChatItem)
				} else {
					this.$emit('withdrawUserMsg', this.showPopChatItem)
				}
			},

			//13，发起好友添加
			sendAddUser() {
				this.$emit('sendAddUser')
			},

			//14，上拉加载
			//14。1，下拉的加载动作，手指未放开
			onPulling(e) {
				//获取，当前第一个个用户的位置
				//this.pullMsgId = this.chatList[0].msgId
				//获取当前长度
				this.oldChatListLength = this.chatList.length
				//console.log(this.oldChatListLength)
			},
			//14.2，下拉刷新，松开了手指
			onRefresh() {
				if (this._freshing) return;
				this._freshing = true;
				//console.log('执行')
				//重新发起请求：请求发送成功以后传入一个回调函数，回调函数停止下拉刷新
				//this.getChatList(this.pageNum)
				this.$emit('getChatListByPage')
			},
			//14.3，刷新完成
			onRestore() {
				var newLengh = this.chatList.length
				var gotoId = newLengh - this.oldChatListLength - 1
				if (gotoId > 1 && this.oldChatListLength != 0) {
					var that = this
					setTimeout(() => {
						this.scrollWithAnimation = true
						this.scrollViewId = ''
						that.$nextTick(function() {
							that.scrollViewId = 'msg' + gotoId
							that.oldChatListLength = 0
						})
					}, 15)

					/* setTimeout(() => {
						this.scrollWithAnimation = true
						this.scrollViewId = 'msg' + gotoId
						setTimeout(() => {
							this.scrollViewId = ''
							this.oldChatListLength = 0
							this.scrollWithAnimation = false
						}, 30)
					}, 10) */

				}
				//console.log(newLengh)

				this.triggered = 'restore'; // 需要重置
				//console.log(this.pullMsgId)
				// if (this.pullMsgId != 0) {
				// 	//滚动到指定位置
				// 	setTimeout(() => {
				// 		this.scrollViewId = 'msg' + this.pullMsgId
				// 		setTimeout(() => {
				// 			this.scrollViewId = ''
				// 			this.pullMsgId = 0
				// 		}, 50)

				// 	}, 10)
				// }
			},
			onAbort() {
				//console.log(4)
			},
			closeRefreshScroll() {
				this.triggered = false;
				this._freshing = false;
				uni.stopPullDownRefresh()
			},

			//15，启动语音发送
			startVoice() {
				this.$nextTick(() => {
					recordManager = uni.getRecorderManager()
					recordManager.onStart(() => {
						console.log('开启动画')
						//展示语音动画
						this.isShowVoiceIcon = true

						recordTimeInterval = setInterval(() => {
							this.recordTime += 1;
							//this.formatedRecordTime = util.formatTime(this.recordTime)

							if (this.recordTime > 10) {
								//结束计时
								clearInterval(recordTimeInterval)
								this.micTouchEnd()
							}
						}, 1000)
					})
					recordManager.onStop((res) => {
						if (this.isCancel) {
							//this.formatedRecordTime = "00:00:00"
							this.isCancel = false
							this.recordTime = 0
						} else {
							if (this.recordTime < 1) {
								this.recordTime = 0
								//console.log('时间太短')
								uni.showToast({
									icon: 'none',
									title: '发送时间太短',
									duration: 1000
								})
								return
							} else {

								uploadFile(res.tempFilePath).then(result => {
									if (result.data.pubInfo.code !== 0) {
										this.isShowClose = false
										this.isShowVoiceIcon = false;
										//归为时长
										this.recordTime = 0
										return uni.$showMsg(result.data.pubInfo.message);
									}
									//var  = result.data.busInfo
									let data = {
										voice: result.data.busInfo,
										time: this.recordTime,
										//标识是否执行
										anmitionPlay: false
									}
									//console.log(result.data.busInfo)
									this.sendMsgByUser(JSON.stringify(data), 3)
									//this.$emit('sendMsgByUser', JSON.stringify(data), 3)
									this.recordTime = 0
								})
							}
						}
					})
				})
			},
			//15.1，按住说话
			micTouchStart(e) {
				// #ifdef APP-PLUS
				plus.device.vibrate(50); //震动
				// #endif

				this.isRecording = true
				recordManager.start({
					format: 'mp3'
				})
			},
			micTouchMove(e) {
				//距离顶部位置
				const pointY = e.touches[0].clientY
				//console.log(this.windowHeight)
				if ((this.windowHeight - 100) > pointY) {
					this.voiceIconTitle = '松开取消发送'
					//console.log('松开')
					this.voiceBgColor = '#FA5251'


					this.isShowClose = true
					this.isCancel = true
				} else {
					this.voiceIconTitle = '正在录音... '
					this.voiceBgColor = '#05C160'

					this.isShowClose = false
					this.isCancel = false
				}
			},
			micTouchCancel(e) {
				this.isRecording = false
				clearInterval(recordTimeInterval)
				recordManager.stop()
				this.isShowVoiceIcon = false;
				this.isShowClose = false

				//this.voiceTime = 0;
				this.voiceIconTitle = '按住 说话';
				this.voiceBgColor = '#05C160'
			},
			micTouchEnd(e) {
				this.isRecording = false
				clearInterval(recordTimeInterval)
				recordManager.stop()
				this.isShowVoiceIcon = false;
				this.isShowClose = false

				//this.voiceTime = 0;
				this.voiceIconTitle = '按住 说话';
				this.voiceBgColor = '#05C160'

			},

			//16，点击语音，播放
			handleAudio(voice) {
				this.$emit("handleAudio", voice)
			},

			//17，有新的消息，展示新的消息提示框
			showNewTips() {
				this.newMsgVisibility = 'visible'
				this.newMsgOpacity = 1
			},
			//17.2，关闭
			closeNewTips() {
				this.newMsgVisibility = 'hidden'
				this.newMsgOpacity = 0
			},
			//17.3，点击新提示，滚动到最底部
			gotoBottomByTips() {
				this.initScrollBar(30)
				this.closeNewTips()
			},

			//消息发送
			sendMsgByUser(msg, types) {
				var data = {
					types,
					msg
				}
				this.$emit('sendMsg', data)
			},

		},
		created() {
			// 初始化状态栏高度
			// uni.getSystemInfo({
			// 	success: res => {
			// 		console.log(res)
			// 		this.statusBarHeight = res.statusBarHeight
			// 	}
			// })

			// 初始化内容高度
			this.getPageInfo()
		},
		mounted() {
			this.getPageInfo()

			//开启上拉刷新
			/* this._freshing = false;
			this.triggered = true; */

			this.startVoice()
		}
	}
</script>

<style lang="scss" scoped>
	//1，页面总高度设置
	.container {
		height: 100vh;
		width: 100%;
		overflow: hidden;
		background-color: #F3F3F3;
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 IOS<11.2*/
		padding-bottom: env(safe-area-inset-bottom);
		/*兼容 IOS>11.2*/
	}

	.history-tips {
		/* width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
		color: #DEDEDE; */

		position: fixed;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 999;
		background-color: rgba(0, 0, 0, 0.15);
		height: 72rpx;
		line-height: 72rpx;
		// transform: translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;
		text-align: center;
		color: #fff;

		// &.show {
		// 	transform: translateY(0);
		// }
	}

	/* #ifdef H5 */
	.container {
		height: calc(100vh - 44px);
		width: 100%;
		overflow: hidden;
		background-color: #F3F3F3;

	}

	/* #endif */


	//2，消息主要内容
	.message {
		background-color: #F3F3F3;
		width: 100%;
		transition: all ease-in-out 0.15s;
	}


	//3，输入框
	.send {
		// display: flex;
		// flex-direction: row;
		// align-items: center;
		// justify-content: space-between;
		/* transition: all 0.1s ease; */
		position: relative;
		width: 100%;
		height: 110rpx;

	}

	.send-new-msg {
		position: absolute;
		z-index: 9;
		top: -80rpx;
		right: 30rpx;
		width: fit-content;
		height: 60rpx;
		line-height: 60rpx;
		padding: 0 20rpx;
		background-color: #333;
		border-radius: 10rpx;
		font-size: 28rpx;
		transition: all .3s ease-in-out;

		text {
			color: #fff;
		}

		&:before {
			content: '';
			border-width: 5px;
			border-style: solid;
			border-color: #333 transparent transparent transparent;
			position: absolute;
			bottom: 100%;
			top: 60rpx;
			left: 50%;
			margin-left: -5px;
		}
	}


	.send-row {
		width: 100%;
		height: 110rpx;
		padding: 0 20upx;
		box-sizing: border-box;
		border-top: 2upx solid #EEE;
		border-bottom: 2upx solid #EEE;
		background: #fff;
		// background-color: red;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;

		/* -webkit-overflow-scrolling: auto !important;
		overflow-scrolling: auto !important; */

		.input {
			height: 80upx;
			line-height: 80upx;
			padding: 0 30upx;
			font-size: 34upx;
			border-radius: 60upx;
			background-color: #fff;
			width: calc(100% - 120upx - 20upx - 40upx - 60upx);
			background-color: #FAFAFA;
			margin: 0 10rpx;
		}

		.icon {
			width: 60upx;
			height: 60upx;
			margin: 0 7rpx;
		}

		.btn {
			color: #fff;
			width: 120rpx;
			height: 65rpx;
			font-size: 24rpx;
			line-height: 65rpx;
			text-align: center;
			border-radius: 35rpx;
			background: linear-gradient(to right, #f09b37, #eb632c);
		}
	}

	//4，工具栏框
	.send-file {
		/* transition: all 0.1s ease; */

		.send-file-list {
			display: flex;
			flex-wrap: wrap;
			padding-top: 20rpx;

			.file-box {
				width: 25%;
				position: relative;

				.file-box-item {
					width: 125rpx;
					height: 125rpx;
					position: absolute;
					left: 50%;
					transform: translateX(-50%);
					// height: 80rpx;
					background-color: #fff;
					text-align: center;
					// padding: 15rpx 0;
					border-radius: 20rpx;
					margin-top: 25rpx;

					image {
						margin-top: 15rpx;
						width: 50rpx;
						height: 50rpx;
					}

					.text {
						text-align: center;
						font-size: 26rpx;
					}

					&:active {
						background-color: #DEDEDE;
					}
				}

			}
		}
	}

	.fade-enter-active,
	.fade-leave-active {
		transition: opacity 1.5s; // 设置过渡效果持续时间
	}

	.fade-enter,
	.fade-leave-to {
		opacity: 0; // 设置开始和结束时的透明度
	}
</style>